package web.servlet;

import domain.Account;
import domain.Product;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.AccountService;
import service.CatelogService;

import java.io.IOException;
import java.util.List;
import java.io.PrintWriter;

public class SignOnServlet extends HttpServlet {

    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";

    private String username;
    private String password;

    private String msg;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.password = req.getParameter("password");

        //校验用户输入的正确性
        if (!validate()){
            req.setAttribute("signOnMsg",this.msg);
            req.getRequestDispatcher(SIGN_ON_FORM).forward(req,resp);
        }
        else {
            AccountService accountService = new AccountService();
            Account loginAccount = accountService.getAccount(username,password);
            if (loginAccount == null){
                this.msg = "用户名或密码错误";
                req.setAttribute("signOnMsg",this.msg);
                req.getRequestDispatcher(SIGN_ON_FORM).forward(req,resp);
            }else {
                HttpSession session = req.getSession();
                session.setAttribute("loginAccount",loginAccount);

                if (loginAccount.isListOption()){
                    CatelogService catelogService = new CatelogService();
                    List<Product> myList = catelogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList",myList);
                }

                resp.sendRedirect("main");
            }
        }
    }

    private boolean validate(){
        if (this.username == null || this.username.equals("")){
            this.msg  = "用户名不能为空";
            return false;
        }
        if (this.password == null || this.password.equals("")){
            this.msg = "密码不能为空";
            return false;
        }
        return true;
    }
}
